﻿using AutoMapper;
using Linker.TaskCenter.Services;
using Linker.TaskCenter.Services.Dto;
using Linker.TaskCenter.Tasks.Dto;
using Linker.TaskCenter.Tasks.Entity;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace Linker.TaskCenter
{
    public class TaskCenterApplicationAutoMapperProfile : Profile
    {
        public TaskCenterApplicationAutoMapperProfile()
        {
            // Tasks
            CreateMap<CreateTaskDto, TaskEntity>()
                .ForMember(src => src.Request, opt => opt.MapFrom(src => JsonSerializer.Serialize(src.Request, null)));

            CreateMap<TaskEntity, TaskDto>()
                .ForMember(src => src.Request, opt => opt.MapFrom(src =>
                    !string.IsNullOrEmpty(src.Request)
                        ? JsonSerializer.Deserialize<object>(src.Request, null)
                        : string.Empty
                ))
                .ForMember(src => src.Response, opt => opt.MapFrom(src =>
                    !string.IsNullOrEmpty(src.Response)
                        ? JsonSerializer.Deserialize<object>(src.Response, null)
                        : string.Empty
                ));

            // Services
            CreateMap<CreateOrUpdateServiceDto, ServiceEntity>();
            CreateMap<ServiceEntity, ServiceDto>();
        }
    }
}